<template>
  <div class="app-container">
    <!-- 输入表单 -->
    <el-form :rules="rules"
             :model="teacher"
             ref="teacherForm"
             label-width="80px"
             label-position="right"
    >
      <el-form-item label="讲师姓名" prop="name">
        <el-input v-model="teacher.name" placeholder="最好不要太长" clearable style="width:150px"/>
      </el-form-item>
      <el-form-item label="入驻时间">
        <el-date-picker v-model="teacher.joinDate" clearable value-format="yyyy.MM.dd" style="width:150px"/>
      </el-form-item>
      <el-form-item label="讲师排序">
        <el-input-number v-model="teacher.sort" controls-position="right" :min="0" style="width:150px"/>
      </el-form-item>
      <el-form-item label="讲师头衔">
        <el-select v-model="teacher.level" style="width:150px">
          <!--
          数据类型一定要和取出的json中的一致,否则没法回填
          因此这里value使用动态绑定的值,保证其数据类型是number
          -->
          <el-option :value="1" label="初级讲师"/>
          <el-option :value="2" label="中级讲师"/>
          <el-option :value="3" label="高级讲师"/>
          <el-option :value="4" label="首席讲师"/>
        </el-select>
      </el-form-item>
      <el-form-item label="讲师资历">
        <el-input :rows="5" v-model="teacher.career" placeholder="简单介绍一下讲师" type="textarea" style="width:450px"/>
      </el-form-item>
      <el-form-item label="授课风格">
        <el-input :rows="2" v-model="teacher.style" placeholder="讲师在讲课时的特点" type="textarea" style="width:450px"/>
      </el-form-item>
      <!-- 讲师头像 -->
      <el-form-item label="讲师头像">
        <el-upload
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-success="handleAvatarSuccess"
          :on-error="handleAvatarError"
          ref="upload"
          class="avatar-uploader"
          :action="uploadAction"
        >
          <el-image v-if="teacher.avatar" :src="teacher.avatar" fit="cover"/>
          <i v-else class="el-icon-plus avatar-uploader-icon"/>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button :disabled="saveBtnDisabled" type="primary" @click="saveOrUpdate()">
          <svg-icon icon-class="save"/>
          保存
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { teacherApi } from '@/api'

export default {
  data() {
    return {
      // 初始化讲师默认数据
      teacher: {
        name: '',
        joinDate: '',
        sort: 0,
        level: 1,
        intro: '',
        career: ''
      },
      rules: {
        name: [{ required: true, message: '请输入姓名', trigger: 'blur' }]
      },
      saveBtnDisabled: false, // 保存按钮是否禁用,防止表单重复提交
      uploadAction: process.env.VUE_APP_BASE_API + '/admin/aliyun/oss/avatar/'
    }
  },
  // 页面渲染时从route中拿出id然后取数据
  created() {
    if (this.$route.params.id) {
      this.fetchDataById(this.$route.params.id)
    }
  },
  methods: {
    // 判断是保存还是更新
    saveOrUpdate() {
      // 禁用保存按钮
      this.saveBtnDisabled = true
      this.$refs.teacherForm.validate((valid) => {
        if (valid) {
          if (!this.teacher.id) {
            this.saveData()
          } else {
            this.updateData()
          }
        } else {
          this.$message.warning('请完成必填项')
          this.saveBtnDisabled = false
        }
      })
    },
    // 保存
    saveData() {
      teacherApi.insert(this.teacher).then(response => {
        this.$message.success({
          message: response.message
        })
        this.$router.push({ path: '/teacher' })
      })
    },
    fetchDataById(id) {
      teacherApi.queryById(id).then(response => {
        this.teacher = response.data.item
      })
    },
    // 更新
    updateData() {
      teacherApi.update(this.teacher).then(response => {
        this.$message.success({
          message: response.message
        })
        this.$router.push({ path: '/teacher' })
      })
    },
    // 上传头像之前校验
    beforeAvatarUpload(file) {
      console.log('选择头像')
      // 判断是否是图片
      const suffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const isImage = suffix === 'jpeg' || suffix === 'jpg' || suffix === 'webp' || suffix === 'png'
      console.log(isImage)
      // 判断是否小于2MB
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isImage) {
        this.$message.warning('上传头像图片只支持 JPG/JPEG/WEBP/PNG 格式')
      }
      if (!isLt2M) {
        this.$message.warning('上传头像图片大小不能超过2MB')
      }
      return isImage && isLt2M
    },
    // 上传成功
    handleAvatarSuccess(response) {
      if (response.success) {
        this.teacher.avatar = response.data.url
        // 强制重新渲染
        this.$forceUpdate()
      } else {
        this.$message.error(response.message)
      }
    },
    // http错误处理
    handleAvatarError() {
      console.log('error')
      this.$message.error('HTTP错误 上传文件失败')
    }
  }
}
</script>

<style lang="scss">
@import "~@/assets/css/upload_avatar.scss";
</style>
